package me.shurufa.adapter;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import me.shurufa.R;
import me.shurufa.activities.BookDetailActivity;
import me.shurufa.activities.MyBookCollectDetailActivity;
import me.shurufa.activities.MyBookShelfDetailActivity;
import me.shurufa.activities.MyCommentDetailActivity;
import me.shurufa.bean.Book;
import me.shurufa.db.PersistenceUtils;
import me.shurufa.holder.BaseViewHolder;
import me.shurufa.utils.Constants;
import me.shurufa.utils.Utils;

/**
 * Create by andy (https://github.com/andyxialm)
 * Create time: 16/5/9 09:36
 * Description : 发现模块适配器
 */
public class DiscoveryAdapter extends RecyclerView.Adapter<DiscoveryAdapter.ViewHolder> {

    private List<Book> mDataList;
    private Context mContext;
    private int mFromWhere;


    public DiscoveryAdapter(Context context, List<Book> dataList, int fromWhere) {
        this.mDataList = dataList;
        this.mContext = context;
        this.mFromWhere = fromWhere;
    }

    @Override
    public DiscoveryAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_discovery_book, parent, false);
        return new ViewHolder(v);
    }

    @Override
    public void onBindViewHolder(DiscoveryAdapter.ViewHolder holder, int position) {
        try {
            Book book = mDataList.get(position);
            holder.bind(book);
        } catch (Exception e) {
            Utils.showToast(R.string.sys_err);
        }
    }

    @Override
    public void setHasStableIds(boolean hasStableIds) {
        super.setHasStableIds(hasStableIds);
    }

    /**
     * 添加数据在尾部
     * @param items datalist
     */
    public void append(List<Book> items) {
        if (Utils.isNullForList(items)) {
            return;
        }
        int pos = mDataList.size();
        mDataList.addAll(items);
        notifyItemRangeInserted(pos, items.size());
    }

    @Override
    public int getItemCount() {
        return mDataList.size();
    }

    public void remove(int position) {
        if (mDataList.size() > 0) {
            mDataList.remove(position);
            this.notifyItemRemoved(position);
        }
    }

    public void clear() {
        int size = mDataList.size();
        mDataList.clear();
        this.notifyItemRangeRemoved(0, size);
    }


    // =====ViewHolder=========

    public class ViewHolder extends BaseViewHolder {

        @Bind(R.id.book_img)
        ImageView bookImage;
        @Bind(R.id.book_name)
        TextView bookTitle;
        @Bind(R.id.tv_digest_num)
        TextView tv_digest_num;

        private Book mBook;
        public ViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
            bookTitle.setMaxLines(2);
            addOnClickListener(bookImage);
            addOnClickListener(bookTitle);
        }


        public void bind(Book book) {
            mBook = book;

            // 书评个数
            if (Constants.TYPE_FRAGMENT_MOST_COMMENT == mFromWhere || Constants.TYPE_FRAGMENT_MYCOMMENT == mFromWhere) {
                tv_digest_num.setText(String.format(mContext.getString(R.string.comment_num), mBook.comment_num));
            }
            // 书摘个数
            else {
                tv_digest_num.setText(String.format(mContext.getString(R.string.digest_num), mBook.excerpt_num));
            }

            if (Constants.TYPE_FRAGMENT_NEWEST_BOOK == mFromWhere) {
                if (0 == mBook.excerpt_num && 0 == mBook.comment_num) {
                    tv_digest_num.setText(String.format(mContext.getString(R.string.digest_num), mBook.excerpt_num));
                }

                if (0 == mBook.excerpt_num && 0 != mBook.comment_num) {
                    tv_digest_num.setText(String.format(mContext.getString(R.string.comment_num), mBook.comment_num));
                }
            }

            if (!TextUtils.isEmpty(mBook.title)) {
                bookTitle.setText(mBook.title);
            }

            Glide.with(mContext).load(mBook.image).placeholder(R.drawable.ic_book_loading).error(R.drawable.ic_book_loading).crossFade(600).into(bookImage);
        }

        @Override
        public void onClick(View v) {
            super.onClick(v);
            switch (v.getId()) {
                case R.id.book_img:
                case R.id.book_name:
                    PropertyValuesHolder scaleX = PropertyValuesHolder.ofFloat("scaleX", 1f, 0.9f, 1f);
                    PropertyValuesHolder scaleY = PropertyValuesHolder.ofFloat("scaleY", 1f, 0.9f, 1f);
                    ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(bookImage, scaleX, scaleY);
                    animator.setDuration(150);
                    animator.setInterpolator(new LinearInterpolator());
                    animator.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            handleClick();
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    animator.start();
                    break;
            }
        }

        /**
         * 处理点击
         */
        private void handleClick() {
            // 关闭输入法
            EventBus.getDefault().post(new Intent(Constants.EVENT_CLOSE_INPUT));

            Intent in;
            switch (mFromWhere) {
                case Constants.TYPE_FRAGMENT_NEWEST_BOOK:
                case Constants.TYPE_FRAGMENT_MOST_EXCERPT:
                case Constants.TYPE_FRAGMENT_MOST_COMMENT:
                    in = new Intent(mContext, BookDetailActivity.class);
                    in.putExtra(Constants.ARG_FROM_WHERE, mFromWhere);
                    in.putExtra(Constants.ARG_BOOK, mBook);
                    in.putExtra(Constants.ARG_USER_ID, PersistenceUtils.getUserId());
                    mContext.startActivity(in);
                    break;
                case Constants.TYPE_FRAGMENT_MYCOLLECT:
                    in = new Intent(mContext, MyBookCollectDetailActivity.class);
                    in.putExtra(Constants.ARG_FROM_WHERE, mFromWhere);
                    in.putExtra(Constants.ARG_BOOK, mBook);
                    in.putExtra(Constants.ARG_USER_ID, PersistenceUtils.getUserId());
                    mContext.startActivity(in);
                    break;

                case Constants.TYPE_FRAGMENT_MYSHELF:
                    in = new Intent(mContext, MyBookShelfDetailActivity.class);
                    in.putExtra(Constants.ARG_FROM_WHERE, mFromWhere);
                    in.putExtra(Constants.ARG_BOOK, mBook);
                    in.putExtra(Constants.ARG_USER_ID, PersistenceUtils.getUserId());
                    mContext.startActivity(in);
                    break;

                case Constants.TYPE_FRAGMENT_MYCOMMENT:
                    in = new Intent(mContext, MyCommentDetailActivity.class);
                    in.putExtra(Constants.ARG_FROM_WHERE, mFromWhere);
                    in.putExtra(Constants.ARG_BOOK, mBook);
                    in.putExtra(Constants.ARG_USER_ID, PersistenceUtils.getUserId());
                    mContext.startActivity(in);
                    break;
                default:
                    in = new Intent(mContext, BookDetailActivity.class);
                    in.putExtra(Constants.ARG_FROM_WHERE, mFromWhere);
                    in.putExtra(Constants.ARG_BOOK, mBook);
                    in.putExtra(Constants.ARG_USER_ID, PersistenceUtils.getUserId());
                    mContext.startActivity(in);
                    break;
            }
        }

    }
}
